﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.Drawing.Printing.Internal.DXPageSizeInfo;

namespace WinForm_Mes.WorkingManagement.TeamSet
{
    public partial class EmployeeForm : DevExpress.XtraEditors.XtraForm
    {
        // 定义委托和事件
        public delegate void EmployeeUpdateDelegate();
        public event EmployeeUpdateDelegate EmployeeUpdateEvent;

        // 分页参数
        private int pageIndex = 1;
        private int pageSize = 20;
        private int total = 0;
        private int pageCount = 0;

        // 目标班组ID
        private long targetTeamSetId;
        private string targetTeamSetName;

        // 带参数构造函数，用于接收目标班组ID
        public EmployeeForm(long teamSetId, string teamSetName)
        {
            InitializeComponent();
            targetTeamSetId = teamSetId;
            targetTeamSetName = teamSetName;

            // 设置提示信息
            labelControl1.Text = $"将选中成员分配到班组：{targetTeamSetName}";
        }

        // 默认构造函数
        public EmployeeForm()
        {
            InitializeComponent();
            labelControl1.Visible = false;
        }

        private async void EmployeeForm_Load(object sender, EventArgs e)
        {
            await LoadEmployeeList();
            // 设置GridView多选模式，这会自动在第一列添加复选框
            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CheckBoxRowSelect;
        }

        private async Task LoadEmployeeList()
        {
            try
            {
                // 调用API获取成员列表
                var response = await HttpClientHelper.RequestUrl(
                    RequestType.get,
                    "/api/Scheduling/GetEmployeeList" + $"?PageIndex={pageIndex}&PageSize={pageSize}"
                );

                // 解析返回数据
                var result = JsonConvert.DeserializeObject<EmployeeList<EmployeeModel>>(response);

                if (result != null && result.code == 200)
                {
                    // 绑定数据到GridControl
                    gridControl1.DataSource = result.items;

                    // 更新分页信息
                    total = result.total;
                    pageCount = (int)Math.Ceiling((double)total / pageSize);

                    // 如果需要显示分页信息，可以添加一个标签控件
                    labelControl1.Text = $"共 {total} 条记录，当前第 {pageIndex}/{pageCount} 页";
                }
                else
                {
                    XtraMessageBox.Show($"查询失败：{result?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 获取选中的员工
        public List<EmployeeModel> GetSelectedEmployees()
        {
            var selectedEmployees = new List<EmployeeModel>();

            // 获取所有选中的行
            int[] selectedRows = gridView1.GetSelectedRows();
            foreach (int rowHandle in selectedRows)
            {
                if (gridView1.GetRow(rowHandle) is EmployeeModel employee)
                {
                    selectedEmployees.Add(employee);
                }
            }

            return selectedEmployees;
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            // 获取选中的员工
            var selectedEmployees = GetSelectedEmployees();

            // 检查是否有选中的员工
            if (selectedEmployees.Count == 0)
            {
                XtraMessageBox.Show("请至少选择一名成员", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // 确认操作
            if (XtraMessageBox.Show($"确定要将选中的 {selectedEmployees.Count} 名成员分配到班组吗？", "确认操作",
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }

            try
            {
                // 提取员工ID列表
                var employeeIds = selectedEmployees.Select(a => a.id).ToList();

                // 序列化为JSON数组
                string jsonData = JsonConvert.SerializeObject(employeeIds);
                System.Diagnostics.Debug.WriteLine($"请求数据: {jsonData}");

                // 构建URL，将teamSetId作为查询参数
                string url = $"{MethodGolab.POST_EMPUPDATERANGE}?teamSetId={targetTeamSetId}";
                System.Diagnostics.Debug.WriteLine($"请求URL: {url}");

                // 调用API
                var response = await HttpClientHelper.RequestUrl(
                    RequestType.post,
                    url,
                    jsonData
                );

                // 输出完整响应内容
                System.Diagnostics.Debug.WriteLine($"响应内容: {response}");

                // 解析返回结果
                var result = JsonConvert.DeserializeObject<BaseResponse>(response);

                if (result != null && result.code == 200)
                {
                    XtraMessageBox.Show("成员分配成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    // 触发事件通知父窗体刷新数据
                    if (EmployeeUpdateEvent != null)
                    {
                        EmployeeUpdateEvent.Invoke();
                    }

                    // 设置对话框结果并关闭窗体
                    DialogResult = DialogResult.OK;
                    Close();
                }
                else
                {
                    XtraMessageBox.Show($"成员分配失败：{result?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void labelControl1_Click(object sender, EventArgs e)
        {

        }

        // 上一页按钮点击事件
        private async void PrevPageButton_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                await LoadEmployeeList();
            }
        }

        // 下一页按钮点击事件
        private async void NextPageButton_Click(object sender, EventArgs e)
        {
            if (pageIndex < pageCount)
            {
                pageIndex++;
                await LoadEmployeeList();
            }
        }
    }
}

// 基础响应类
public class BaseResponse
{
    public int code { get; set; }
    public string message { get; set; }
    public object data { get; set; }
}

public class EmployeeList<T>
{
    public int total { get; set; }
    public int pageIndex { get; set; }
    public int pageSize { get; set; }
    public T[] items { get; set; }
    public int code { get; set; }
    public string message { get; set; }
    public object data { get; set; }
}

public class EmployeeModel
{
    public long id { get; set; }
    public string employeeCode { get; set; }
    public string employeeName { get; set; }
    public long teamSetId { get; set; }
}